package com.gs.synedocket.control;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.gs.synedocket.R;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.util.ImageUtil;
import com.gs.synedocket.util.OKHttpUtil;
import com.gs.synedocket.util.StringUtil;


public class SignPhotoView extends FrameLayout {

    private Context context;
    private ImageView imageView;

    public SignPhotoView(@NonNull Context context) {
        super(context);
        init(context, null);
    }

    public SignPhotoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public SignPhotoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public SignPhotoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs == null) {
            return;
        }

        this.context = context;

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SignPhotoView);
        String title = ta.getString(R.styleable.SignPhotoView_sign_photo_title_text);

        View view = LayoutInflater.from(context).inflate(R.layout.item_sign_photo, this, false);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        tvTitle.setText(title);
        imageView = view.findViewById(R.id.iv_photo);
        addView(view);
        ta.recycle();
    }

    public void setImageUrl(String url) {
        imageView.setImageResource(0);
        if (TextUtils.isEmpty(url)) {
            return;
        }
        if (StringUtil.isLocalPhoto(url)) {
            ImageUtil.loadImg(context, ImageUtil.base64ToByte(url.substring(AllConstants.PHOTO_NAME.length())), imageView);
        } else {
            ImageUtil.loadImg(context, OKHttpUtil.IMG_URL + url, imageView);
        }
    }
}
